﻿// <copyright file="CreateActivityRequest.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2009-04-17</date>
// <summary>Class definition for CreateActivityRequest</summary>

namespace MyOpenSpace
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Windows.Browser;
    using Synergist;

    /// <summary>
    /// MySpace Create Activity Request CLR object
    /// </summary>
    /// <remarks>
    /// <a href="http://wiki.developer.myspace.com/index.php?title=MDP_Activities:_Getting_Started">MDP Activities: Getting Started</a>
    /// Typical usage would be:
    /// <list type="number">
    /// <item>
    ///     <description>derive a class from this request</description>
    /// </item>
    /// <item>
    ///     <description>add parameters specific to this activity request</description>
    /// </item>
    /// <item>
    /// <description>Override <c>OnGetTemplateParameters()</c> to add the parameters to the dictionary
    /// </description>
    /// </item>
    /// </list>
    /// </remarks>
    public class CreateActivityRequest
    {
        #region Fields
        /// <summary>
        /// the OpenSocial JScript object
        /// </summary>
        private ScriptObject openSocial;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the CreateActivityRequest class
        /// </summary>
        public CreateActivityRequest()
        {
            this.MediaItems = new Collection<string>();

            this.Priority = "opensocial.CreateActivityPriority.HIGH";

            try
            {
                this.openSocial = HtmlPage.Window.Eval("opensocial") as ScriptObject;
            }
            catch (InvalidOperationException ioe)
            {
                System.Diagnostics.Debug.WriteLine("Not running in an OpenSocial container: {0}", ioe.Message);
            }
        }
        #endregion

        #region Delegates
        /// <summary>
        /// Activity Created delegate
        /// </summary>
        /// <param name="response">the script response</param>
        private delegate void ActivityCreated(ScriptObject response);
        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the template's Name
        /// </summary>
        [Description("The template's Name as entered in the MySpace Developer Platform")]
        public string TemplateName { get; set; }

        /// <summary>
        /// Gets or sets the priority for the activity
        /// </summary>
        [Description("opensocial.CreateActivityPriority.HIGH or opensocial.CreateActivityPriority.Low")]
        public string Priority { get; set; }

        /// <summary>
        /// Gets the list of media items
        /// </summary>
        public Collection<string> MediaItems { get; private set; }

        #endregion

        #region Methods
        /// <summary>
        /// Make the request to create the activity
        /// </summary>
        /// <remarks>You should save the state of the control to isolated storage beforem making 
        /// this request because the opensocial.requestCreateActivity() method will trigger a popup 
        /// window in MySpace which removes the Silverlight application from the DOM.</remarks>
        public void MakeRequest()
        {
            if (this.openSocial == null)
            {
                return;
            }

            var parameters = HtmlPage.Window.CreateInstance("Object");

            parameters.SetProperty("opensocial.Activity.Field.TITLE_ID".Eval(), this.TemplateName);

            var templateParameters = new Dictionary<string, object>();

            this.OnGetTemplateParameters(templateParameters);

            if (templateParameters.Count > 0)
            {
                var associative = HtmlPage.Window.CreateInstance("Object");

                foreach (var item in templateParameters)
                {
                    associative.SetProperty(item.Key, item.Value);
                }

                parameters.SetProperty("opensocial.Activity.Field.TEMPLATE_PARAMS".Eval(), associative);
            }

            var mediaItemArray = HtmlPage.Window.CreateInstance("Array");

            foreach (var mediaItem in this.MediaItems)
            {
                var newMediaItem = this.openSocial.Invoke("newMediaItem", string.Empty, mediaItem) as ScriptObject;

                mediaItemArray.Invoke("push", newMediaItem);
            }

            parameters.SetProperty("opensocial.Activity.Field.MEDIA_ITEMS".Eval(), mediaItemArray);

            var activity = this.openSocial.Invoke("newActivity", parameters) as ScriptObject;

            var priority = this.Priority.Eval();

            var activityCreated = new ActivityCreated(this.OnActivityCreated);

            this.openSocial.Invoke("requestCreateActivity", activity, priority, activityCreated);
        }

        /// <summary>
        /// Add the parameters for this activity request
        /// </summary>
        /// <param name="parameters">the parameters collection</param>
        public virtual void OnGetTemplateParameters(IDictionary<string, object> parameters)
        {
        }

        #endregion

        #region Implementation

        /// <summary>
        /// Callback to handle when activity has been creted
        /// </summary>
        /// <param name="param1">the first return parameter</param>
        private void OnActivityCreated(ScriptObject param1)
        {
            var responseItem = new opensocial.ResponseItem(param1);

            if (responseItem.hadError())
            {
                System.Diagnostics.Debug.WriteLine(responseItem.getErrorMessage());
                System.Diagnostics.Debug.WriteLine(responseItem.getErrorCode());
            }
        }

        #endregion
    }
}
